<template>
  <div class="list-transition-demo">
    <h2>列表过渡动画</h2>

    <div class="controls">
      <input
        v-model="newItem"
        @keyup.enter="addItem"
        placeholder="输入新项目，按回车添加"
        class="input-field"
      />
      <button @click="addItem" :disabled="!newItem.trim()">添加</button>
      <button @click="shuffle">打乱顺序</button>
      <button @click="reset">重置列表</button>
    </div>

    <TransitionGroup name="list" tag="ul" class="todo-list">
      <li v-for="item in items" :key="item.id" class="todo-item" @click="removeItem(item.id)">
        <span class="item-content">{{ item.text }}</span>
        <span class="remove-hint">点击删除</span>
      </li>
    </TransitionGroup>
  </div>
</template>
<script setup>
import { ref } from 'vue'

const newItem = ref('')
const items = ref([
  { id: 1, text: '学习 Vue3 基础' },
  { id: 2, text: '掌握组合式 API' },
  { id: 3, text: '学习过渡动画' },
  { id: 4, text: '构建完整项目' },
])

let nextId = 5

const addItem = () => {
  if (newItem.value.trim()) {
    items.value.push({
      id: nextId++,
      text: newItem.value.trim(),
    })
    newItem.value = ''
  }
}

const removeItem = (id) => {
  items.value = items.value.filter((item) => item.id !== id)
}

const shuffle = () => {
  items.value = items.value.sort(() => Math.random() - 0.5)
}

const reset = () => {
  items.value = [
    { id: 1, text: '学习 Vue3 基础' },
    { id: 2, text: '掌握组合式 API' },
    { id: 3, text: '学习过渡动画' },
    { id: 4, text: '构建完整项目' },
  ]
  nextId = 5
}
</script>
<style scoped>
.list-transition-demo {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.controls {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: center;
}

.input-field {
  flex: 1;
  min-width: 200px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

button {
  padding: 10px 15px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

button:not(:disabled):hover {
  background: #2980b9;
}

.todo-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.todo-item {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 15px 20px;
  margin: 8px 0;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: transform 0.2s ease;
}

.todo-item:hover {
  transform: translateX(5px);
}

.item-content {
  font-weight: 500;
}

.remove-hint {
  font-size: 12px;
  opacity: 0.7;
}

/* 列表过渡动画 */
.list-enter-active,
.list-leave-active {
  transition: all 0.3s ease;
}

.list-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}

.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

/* 移动过渡 */
.list-move {
  transition: transform 0.3s ease;
}
</style>
